package chat.keepWind.handle;

import java.awt.Color;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.RandomAccessFile;
import java.util.List;
import java.util.Map;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;

import chat.keepWind.bean.Config;
import chat.keepWind.bean.DataPackage;
import chat.keepWind.bean.User;
import chat.keepWind.event.ReceiveFile;
import chat.keepWind.event.SendFile;
import chat.keepWind.event.SendMessage;
import chat.keepWind.ui.ChatUI;
import chat.keepWind.ui.FriendTree;
import chat.keepWind.util.ChatUtil;
import chat.keepWind.util.GlobalConst;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

public class KeepWindInboundHandler extends SimpleChannelInboundHandler<DataPackage> {
	
	
	@Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace(); 
        ctx.close();
    }

    @SuppressWarnings("unchecked")
	@Override
    public void channelRead0(ChannelHandlerContext ctx, final DataPackage data) throws Exception {
         
    	//上线通知，需带上昵称
    	if(data.getMsgType().equals(GlobalConst.TYPE_LOGIN)){
    		
			List<User> onlineUsers = (List<User>)ChatUtil.dataMap.get("onlineUsers");
			
			Config config = (Config)ChatUtil.dataMap.get("config");
			
			String nickName = data.getNickName();
			Map<String,User> userMap = config.getUserMap();
			User user = userMap.get(data.getFromIp());
			if(user!=null){
				nickName = user.getNickName();
			}
			
			User tmp = ChatUtil.isExsitsIp(onlineUsers, data.getFromIp());
			if(tmp==null){
				User u = new User();
				u.setIp(data.getFromIp());
				u.setNickName(nickName);
				onlineUsers.add(u);//加入用户
	    		
	    		//加入到界面用户列表
	    		FriendTree userTree = (FriendTree)ChatUtil.dataMap.get("userTree");
	    		userTree.addOnlineUser(data.getFromIp(),nickName);
			}
			
			//修改对话框状态
    		Map<String,ChatUI> chats = (Map<String,ChatUI>)ChatUtil.dataMap.get("chats");
    		ChatUI chatui = chats.get(data.getFromIp());
    		if(chatui!= null){
    			chatui.getWin().setTitle("与用户(" + nickName + ")对话中");
    		}
    		
			//如果是 上线通知，需要反馈
			DataPackage ret = new DataPackage();
    		//ret.setFromIp("127.0.0.1");
			ret.setFlag((byte)2);
    		ret.setFromIp((String)ChatUtil.dataMap.get("ip"));
    		ret.setPort(data.getPort());
    		ret.setToIp(data.getFromIp());
    		ret.setNickName(config.getLocalNickName());
    		ret.setMsgType(GlobalConst.TYPE_LOGIN_REP);
    		ret.setMsgContent("".getBytes(CharsetUtil.UTF_8));
    		ctx.writeAndFlush(ret);
    		
    	}else if(data.getMsgType().equals(GlobalConst.TYPE_TXT)){
    		//接收到普通文本消息
    		
    		String nickName = ChatUtil.getNickName(data.getFromIp());
    		
    		
    		ChatUI chat = ChatUtil.openChat(data.getFromIp(),nickName);
    		
    		
    		String head = "\n"+nickName+"（"+data.getSendTime()+"）"+"：\n";
    		
    		ChatUtil.showTalk(chat, head,new String(data.getMsgContent(),CharsetUtil.UTF_8));
    		
    	}else if(data.getMsgType().equals(GlobalConst.TYPE_FILE)){
    		//接收到 文件类型消息
    		
    		final String nickName = ChatUtil.getNickName(data.getFromIp());
    		
    		ChatUI chat = ChatUtil.openChat(data.getFromIp(),nickName);
    		
    		Document doc = chat.getDsiplChatArea().getStyledDocument();
    		
    		SimpleAttributeSet headAttr = new SimpleAttributeSet();
    		StyleConstants.setBold(headAttr, true);
    		StyleConstants.setForeground(headAttr, new Color(66, 141, 94));
    		
    		String head = "\n"+nickName+"（"+data.getSendTime()+"）"+"：\n";
    		String text = "文件（"+data.getFileName()+"）";
    		try {
    			doc.insertString(doc.getLength(), head,  headAttr);
    			doc.insertString(doc.getLength(), text,  new SimpleAttributeSet());
    		} catch (BadLocationException e) {
    			e.printStackTrace();
    		}
    		//设置 选中的内容，为最后一个字符之后的空字符
    		chat.getDsiplChatArea().setCaretPosition(doc.getLength());
    		
    		
    		final JButton but = new JButton();
    		
    		/*but.setFont(new Font("黑体", Font.PLAIN, 12));
    		but.setForeground(SystemColor.menuText);
    		but.setText("接受");
    		but.setUI(new BEButtonUI()
    				.setNormalColor(BEButtonUI.NormalColor.lightBlue));*/
    		but.setIcon(new ImageIcon(Toolkit
    				.getDefaultToolkit().getImage(getClass().getResource("/picture/rcvBtn1.png"))));
    		but.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					
					ChatUI chat = ChatUtil.openChat(data.getFromIp(),nickName);
					
					JFileChooser chooser = new JFileChooser(".");
					chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
					chooser.showOpenDialog(chat.getWin().getRootPane());
					File file = chooser.getSelectedFile();
					
					DataPackage dataPkg = new DataPackage();
					dataPkg.setFromIp(data.getToIp());
					dataPkg.setToIp(data.getFromIp());
					dataPkg.setMsgType(GlobalConst.TYPE_SND_FILE);
					dataPkg.setSrcPath(data.getSrcPath());
					dataPkg.setFileName(data.getFileName());
					dataPkg.setDistPath(file.getPath()+File.separator+data.getFileName());
					dataPkg.setFileLen(data.getFileLen());
				
					
					but.setEnabled(false);
					but.setIcon(new ImageIcon(Toolkit
		    				.getDefaultToolkit().getImage(getClass().getResource("/picture/rcvBtn2.png"))));
					
					//开启线程，接收文件
					new Thread(new Runnable() {
						@Override
						public void run() {
							ReceiveFile rf = new ReceiveFile();
							rf.receive();
						}
					}).start();
					
					try {
						Thread.sleep(500);
					} catch (InterruptedException e1) {
						e1.printStackTrace();
					}
					
					//通知 发送
					SendMessage snd = new SendMessage();
					snd.send(dataPkg.getToIp(), dataPkg);
					
				}
    		});
    		
    		chat.getDsiplChatArea().insertComponent(but);
    		
    	}else if(data.getMsgType().equals(GlobalConst.TYPE_SND_FILE)){
    		//接收到  发送文件的消息
    		String fromIp = data.getFromIp();
        	String toIp = data.getToIp();
        	File file = new File(data.getSrcPath());
        	
           
	        final DataPackage ret = new DataPackage();
	        ret.setFromIp(toIp);
	        ret.setToIp(fromIp);
	        
	        ret.setFileLen(file.length());
	        ret.setSrcPath(data.getSrcPath());
	        ret.setDistPath(data.getDistPath());
	        ret.setFileName(data.getFileName());
	        //另起线程发送文件
	        new Thread(new Runnable() {
				@Override
				public void run() {
					
					SendFile sndFile = new SendFile();
					sndFile.send(ret.getToIp(), ret);
				}
			}).start();
    	}
    	/*else if(data.getMsgType().equals(GlobalConst.TYPE_FILE_COMPLETE)){
    		//文件传输完成
    		 //聊天界面 显示 已接受 信息
        	String nickName = ChatUtil.getNickName(data.getFromIp());
    		
    		ChatUI chat = ChatUtil.openChat(data.getFromIp(),nickName);
    		Document doc = chat.getDsiplChatArea().getStyledDocument();
    		
    		SimpleAttributeSet headAttr = new SimpleAttributeSet();
    		StyleConstants.setBold(headAttr, true);
    		StyleConstants.setForeground(headAttr, new Color(66, 141, 94));
    		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    		
    		String head = "\n"+nickName+"（"+sdf.format(new Date())+"）"+"：\n";
    		String text = "文件（"+data.getFileName()+"）已接受";
    		try {
    			doc.insertString(doc.getLength(), head,  headAttr);
    			doc.insertString(doc.getLength(), text,  new SimpleAttributeSet());
    		} catch (BadLocationException e) {
    			e.printStackTrace();
    		}
    		//设置 选中的内容，为最后一个字符之后的空字符
    		chat.getDsiplChatArea().setCaretPosition(doc.getLength());
    	}*/
    	else if(data.getMsgType().equals(GlobalConst.TYPE_RCV_CAPIMG)){
    		//接收到截图
    		
    		long start = data.getPoint();
			//RandomAccessFile randomAccessFile = new RandomAccessFile(data.getDistPath(), "rw");
			RandomAccessFile randomAccessFile = new RandomAccessFile(GlobalConst.CAP_IMG_PATH+data.getFileName(), "rw");
          
            long remain =  data.getFileLen()-start;//剩余的
            
            randomAccessFile.seek(start); //将文件指针定位到start
            
            randomAccessFile.write(data.getMsgContent());//从start字节开始写数据
            randomAccessFile.close();
            
            /*if(remain<GlobalConst.BYTE_NUM){
            	
            }*/
    	}else if(data.getMsgType().equals(GlobalConst.TYPE_LOGOUT)){
    		//接收到用户 下线消息
    		//System.out.println("---下线"+data.getFromIp());
    		
    		//修改对话框状态
    		Map<String,ChatUI> chats = (Map<String,ChatUI>)ChatUtil.dataMap.get("chats");
    		ChatUI chatui = chats.get(data.getFromIp());
    		if(chatui!= null){
    			String nickName = ChatUtil.getNickName(data.getFromIp());
        		
    			chatui.getWin().setTitle("用户(" + nickName + ")已离线");
    		}
    		//移除onlineUsers中用户
    		List<User> onlineUsers = (List<User>)ChatUtil.dataMap.get("onlineUsers");
    		for(User user:onlineUsers){
    			if(data.getFromIp().equals(user.getIp())){
    				onlineUsers.remove(user);
    				break;
    			}
    		}
    		//删除用户树节点
    		FriendTree userTree = (FriendTree)ChatUtil.dataMap.get("userTree");
    		userTree.delOfflineUser(data.getFromIp());
    		
    	}
    }
    
   
    
}
